<?php

namespace app\admin\controller;
use app\admin\model\BydOrderSon;
use think\db;
use app\admin\model\BydOrderTui;
use app\common\controller\Backend;

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class BydShopOrder extends Backend
{
    
    /**
     * BydShopOrder模型对象
     * @var \app\admin\model\BydShopOrder
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\BydShopOrder;
        $this->view->assign("dzg", $this->model->dzg());
        $this->view->assign("statesList", $this->model->getStatesList());
        $this->view->assign("stateList", $this->model->getStateList());
        $this->view->assign("statusList", $this->model->getStatusList());
    $this->view->assign("express", $this->model->getexpressList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['bydshop'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);
                        
            foreach ($list as $k=>$row) {

                $goods = BydOrderSon::where(['porderid'=>$row['orderid']])->select();
                $str  ='';
                foreach ($goods as $j=>$g) {
                    $img = '';
                    if(trim($g['good_image']) != '')  $img = "<img src='{$g['good_image']}' style='width:30px;height:30px;'>";
                    $str .= '<table border="1" style=\'border-color:#dcdcdc\'>';
                    $str .= "<tr><th rowspan='2'>{$img}</th><th>{$g['productname']}</th></tr><tr><th>{$g['good_code']}</th></tr>";
                    $str .= '</table>';
                }

                $row['good_info'] = $str;
                $list[$k] = $row;
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 查看详情
     */
    public function shouhou($ids){
        $find = array();
        $row = $this->model->get($ids);
        $this->view->assign("row", $row);
        //print_r($row['id']);die;
       // $shops=\app\admin\model\BydShopOrder::where('id',$ids)->find();
        $shops= Db::table('fa_byd_shop_order')
            ->alias('o')
            ->join('fa_byd_order_tuishop s','o.orderid = s.orderid')
//            ->join('fa_byd_shop p','p.id = s.productid')
            ->where('o.id',$row['id'])
            ->field('o.orderid,o.state,o.tuiprice,o.image,o.tuik_ly,s.productname,s.specidsize,s.num,s.price')
            ->select();


        $this->view->assign("find", $shops);

        //$this->view->assign('find', $find);
        return $this->view->fetch();
//      return $ids;
    }
    /**
     * 查看详情
     */
  public function detail($ids){

    $find = array();
      $row = $this->model->get($ids);
      $this->view->assign("row", $row);
      $shops=\app\admin\model\BydShopOrder::where('id',$ids)->find();

      #查询子订单，如果无查询对应商品
      $sonOrders=BydOrderSon::where('porderid',$shops['orderid'])->select();
       if($sonOrders){
           foreach ($sonOrders as $v){
                $v['sprice'] = $v['price']/$v['num'];
                $find[] = $v;
           }
       }
 
           $this->view->assign("find", $find);

      //$this->view->assign('find', $find);
      return $this->view->fetch();
//      return $ids;
  }
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
$find = array();
      $shops=\app\admin\model\BydShopOrder::where('id',$ids)->find();

      #查询子订单，如果无查询对应商品
      $sonOrders=BydOrderSon::where('porderid',$shops['orderid'])->select();
       if($sonOrders){
           foreach ($sonOrders as $v){
                $v['sprice'] = $v['price']/$v['num'];
                $find[] = $v;
           }
       }
           $this->view->assign("find", $find);

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            //print_r($params);die;
            if($params['state'] == 2 && (trim($params['express']) == 'express' || trim($params['expressorder'] == '')))
            {
                $this->error('物流信息不能空！');
            }
            if(!empty($params['context'])){

               $add=new \app\admin\model\BydSdexpress();
               $add->data([
                   'context'=>$params['context'],
                   'status'=>$params['exstatus'],
                   'time'=>$params['time'],
                   'orderid'=>$shops['orderid']
               ]);
               $add->save();
            }
            if(!empty($params['express'])){
                $expree=\app\admin\model\BydShopExpress::where('id',$params['express'])->find();
                $params['expressname']=$expree['title'];
            }
            
            if ($params) {
              if($params['state']==6){
                  $order=\app\admin\model\BydShopOrder::where('id',$row['id'])->find();
                  $add = new BydOrderTui();
                  $add->data([
                      'price'  =>$order['price'],
                      'orderid'  =>$order['orderid'],
                      'content' =>  $order['content'],
                      'user_id' =>  $order['user_id'],
                      'tuik_ly'=>$order['tuik_ly']
                  ]);
                  $add->save();
              }
              if($params['states']==3){
                  $order=\app\admin\model\BydShopOrder::where('id',$row['id'])->find();
                  $add = new BydOrderTui();
                  $add->data([
                      'state'=>4,
                      'price'  =>$order['tuiprice'],
                      'orderid'  =>$order['orderid'],
                      'content' =>  $order['tuik_ly'],
                      'user_id' =>  $order['user_id'],
                      'image'=>$order['image']
                  ]);
                  $add->save();
              }
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    /**
     * 检测是否有新退货消息
     */
    public function isHaveNewAfter()
    {
        $cache=\think\Cache::get('name');
       if(!empty($cache)){
           $tips = 'aftersale:tips:number';
           //edis = (new Redis())->getRedis();
           $tipsNumber = rand();
           $this->success('获取新退货消息数量成功', null, $tipsNumber);
       }

    }

    /**
     * 已确认新退货消息
     */
    public function handleTui()
    {
        $type = $this->request->post('type');
        $tips = 'aftersale:tips:number';
        $tipsNumber = rand();
        \think\Cache::rm('name');
        $this->success('确认新退货消息成功', null, $type);
    }
    /**
     * 检测是否有新订单消息
     */
    public function isHaveNewAfters()
    {
        $xd=\think\Cache::get('xd');//新订单
        $name=\think\Cache::get('name');//售后
        $tuit=\think\Cache::get('tuit');//退款
        $px=\think\Cache::get('px');//培训费用申请
        $fw=\think\Cache::get('fw');//是否提供fw
        $bbs=\think\Cache::get('bbs');//销售员
        $sqsq=\think\Cache::get('sqsq');//业务地图提交申请
        $des=\think\Cache::get('des');//设计师申请
        $desyy=\think\Cache::get('desyy');//设计师处理订单
        $yydes=\think\Cache::get('yydes');//预约设计师
        $paymoney=\think\Cache::get('paymoney');//c支付定金
        if(!empty($xd)){
            $tips = 'aftersale:tips:number';
            //edis = (new Redis())->getRedis();
            $tipsNumber = rand();
            $this->success('获取新订单消息数量成功', null, 1);
        }elseif (!empty($name)){
            $this->success('获取售后消息数量成功', null, 2);
        }elseif (!empty($tuit)){
            $this->success('获取新退款消息数量成功', null, 3);
        }elseif (!empty($px)){
            $this->success('获取新订单消息数量成功', null, 4);
        }elseif (!empty($fw)){
            $this->success('获取新订单消息数量成功', null, 5);
        }elseif (!empty($bbs)){
            $this->success('获取新订单消息数量成功', null, 6);
        }elseif (!empty($sqsq)){
            $this->success('获取新订单消息数量成功', null, 7);
        }elseif (!empty($des)){
            $this->success('获取新订单消息数量成功', null, 8);
        }elseif (!empty($desyy)){
            $this->success('获取新订单消息数量成功', null, 9);
        }elseif (!empty($yydes)){
            $this->success('获取新订单消息数量成功', null, 10);
        }elseif (!empty($paymoney)){
            $this->success('获取新订单消息数量成功', null, 11);
        }else{
            $this->error('获取新订单消息数量失败', null, $desyy);
        }

    }

    /**
     * 已确认新订单消息
     */
    public function handleTuis()
    {
        $type = $this->request->post('type');
//
        \think\Cache::rm('xd');
        \think\Cache::rm('name');
        \think\Cache::rm('tuit');
        \think\Cache::rm('px');
        \think\Cache::rm('fw');
        \think\Cache::rm('bbs');
        \think\Cache::rm('sqsq');
        \think\Cache::rm('des');
        \think\Cache::rm('desyy');
        \think\Cache::rm('yydes');
        \think\Cache::rm('paymoney');
        if($type=='xd'){
            \think\Cache::rm('xd');
            $this->success('确认新订单消息成功', 'https://bao.scwushen.com/zorOpABXJt.php/byd_shop_order/index?ref=addtabs', $type);
        }elseif ($type=='name'){
            \think\Cache::rm('name');
            $this->success('确认新订单消息成功', 'https://bao.scwushen.com/zorOpABXJt.php/byd_shop_order/index?ref=addtabs', $type);
        }elseif ($type=='tuit'){
            \think\Cache::rm('tuit');
            $this->success('确认新订单消息成功', 'https://bao.scwushen.com/zorOpABXJt.php/byd_order_tui?ref=addtabs', $type);
        }elseif ($type=='px'){
            \think\Cache::rm('px');
            $this->success('确认新订单消息成功', 'https://bao.scwushen.com/zorOpABXJt.php/train?ref=addtabs', $type);
        }elseif ($type=='fw'){
            \think\Cache::rm('fw');
            $this->success('确认新订单消息成功', 'https://bao.scwushen.com/zorOpABXJt.php/twotg?ref=addtabs', $type);
        }elseif ($type=='bbs'){
            \think\Cache::rm('bbs');
            $this->success('确认新订单消息成功', 'https://bao.scwushen.com/zorOpABXJt.php/byd_user_sale?ref=addtabs', $type);
        }elseif ($type=='sqsq'){
            \think\Cache::rm('sqsq');
            $this->success('确认新订单消息成功', 'https://bao.scwushen.com/zorOpABXJt.php/sole_agency?ref=addtabs', $type);
        }elseif ($type=='des'){
            \think\Cache::rm('des');
            $this->success('确认新订单消息成功', 'https://bao.scwushen.com/zorOpABXJt.php/byd_designer?ref=addtabs', $type);
        }elseif ($type=='desyy'){
            \think\Cache::rm('desyy');
            $this->success('确认新订单消息成功', 'https://bao.scwushen.com/zorOpABXJt.php/byd_designer_make?ref=addtabs', $type);
        }elseif ($type=='yydes'){
            \think\Cache::rm('yydes');
            $this->success('确认新订单消息成功', 'https://bao.scwushen.com/zorOpABXJt.php/byd_designer_make?ref=addtabs', $type);
        }elseif ($type=='paymoney'){
            \think\Cache::rm('paymoney');
            $this->success('确认新订单消息成功', 'https://bao.scwushen.com/zorOpABXJt.php/byd_designer_make?ref=addtabs', $type);
        }else{
            $tips = 'aftersale:tips:number';
            $tipsNumber = rand();

            $this->success('确认新订单消息成功', '/zorOpABXJt.php/byd_shop_order/index', $type);
        }

    }
}
